<template>
  <div class="home page-container">
    <!-- 导航栏 -->
    <van-nav-bar class="custom-nav" fixed placeholder>
      <template #left>
        <van-icon name="menu-o" size="24" @click="handleMenu" />
      </template>
      <template #title>
        <van-tabs v-model:active="activeTab" swipeable animated color="#fe2c55" title-inactive-color="#666"
          title-active-color="#333" line-height="2px" @change="handleTabChange">
          <van-tab v-for="tab in tabs" :key="tab.key" :title="tab.title" />
        </van-tabs>
      </template>
      <template #right>
        <van-icon name="search" size="24" @click="goToSearch" />
      </template>
    </van-nav-bar>

    <!-- 内容区域 -->
    <div class="content-container" ref="scrollContainerRef">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh" success-text="刷新成功">
        <FsBookVirtualWaterfall2 
          ref="waterfallRef"
          :column="2" 
          :gap="8" 
          :pageSize="20" 
          :request="handleRequest"
        >
          <template #item="{ item, imageHeight }">
            <activity-card 
              :activity="item" 
              @click="goToDetail(item.id)"
              :style="{
                height: `${imageHeight}px`,
                width: '100%'
              }"
            >
              <template #img>
                <img 
                  :src="item.cover" 
                  v-if="item.cover" 
                  class="activity-image"
                  :style="{ height: `${imageHeight}px` }"
                />
              </template>
            </activity-card>
          </template>
        </FsBookVirtualWaterfall2>
      </van-pull-refresh>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
// import { Waterfall, LazyImg } from 'vue-waterfall-plugin-next'
// import 'vue-waterfall-plugin-next/dist/style.css'
import ActivityCard from '@/components/activity/ActivityCard.vue'
import { activityApi } from '@/api'
import  FsBookVirtualWaterfall2  from './FsBookVirtualWaterfall2.vue'
import type { ICardItem } from './tpye1'
const router = useRouter()
const activeTab = ref(0)
const tabs = [
  { key: 'recommend', title: '推荐' },
  { key: 'following', title: '关注' },
  { key: 'nearby', title: '附近' }
]

// 数据相关状态
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const currentPage = ref(1)
const pageSize = 10

// 处理请求的函数
const handleRequest = async (page: number, size: number): Promise<ICardItem[]> => {
  console.log('开始请求数据:', { page, size, type: tabs[activeTab.value].key })
  
  if (loading.value) return []
  
  loading.value = true
  try {
    const response = await activityApi.getActivityList({
      page,
      pageSize: size,
      type: tabs[activeTab.value].key
    })
    
    console.log('API返回数据:', response)

    // 检查响应数据结构
    if (!response?.data?.list?.length) {
      return []
    }

    // 确保数据格式正确
    const formattedList = response.data.list.map(item => ({
      id: item.id,
      width: 345,  // 根据实际屏幕宽度调整
      height: item.cover ? 200 : 100,
      cover: item.cover || '',
      title: item.title || '',
      startTime: item.start_time || item.startTime,
      content: item.content || '',
      location: item.location || '',
      ...item
    }))

    console.log('格式化后的数据:', formattedList)
    return formattedList
  } catch (error) {
    console.error('请求失败:', error)
    showToast('获取数据失败')
    return []
  } finally {
    loading.value = false
  }
}

// 刷新处理
const onRefresh = async () => {
  finished.value = false;
  currentPage.value = 1;
  refreshing.value = false;
  // 瀑布流组件会自动重新加载数据
};

// 格式化数据
const formatActivityData = (item: any) => {
  return {
    ...item,
    id: item.id,
    width: 100,  // 设置默认宽度
    height: item.cover ? 200 : 100, // 根据是否有封面设置默认高度
    startTime: item.startTime || item.start_time,
  };
};

// 页面事件处理
const handleMenu = () => {
  showToast('菜单功能开发中')
}

const goToSearch = () => {
  router.push('/search')
}

const handleTabChange = () => {
  if (waterfallRef.value) {
    waterfallRef.value.reset()
  }
}

const goToDetail = (id: number) => {
  router.push(`/activity/detail/${id}`)
}

// 生命周期
onMounted(() => {
  nextTick(() => {
    // fetchData()
  })
})

// 添加 waterfallRef 的类型
const waterfallRef = ref<InstanceType<typeof FsBookVirtualWaterfall2> | null>(null)
</script>

<style lang="scss" scoped>
.home {
  min-height: 100vh;
  background-color: #eee;
  display: flex;
  flex-direction: column;

  .custom-nav {
    :deep(.van-nav-bar__content) {
      height: 44px;
    }

    :deep(.van-nav-bar__title) {
      width: 70%;
      display: flex;
      justify-content: center;
    }

    :deep(.van-tabs) {
      width: 100%;
      height: 44px;

      .van-tabs__wrap {
        height: 100%;
      }

      .van-tabs__nav {
        background: transparent;
      }

      .van-tab {
        padding: 0 12px;
        color: #666;
        font-size: 15px;
        line-height: 44px;
      }

      .van-tab--active {
        color: #333;
        font-weight: 600;
      }

      .van-tabs__line {
        bottom: 6px;
        height: 2px;
      }
    }

    :deep(.van-icon) {
      color: #333;
    }
  }

  .content-container {
    flex: 1;
    height: calc(100vh - 44px);
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    background: #f5f5f5;
    padding: 8px;

    :deep(.fs-virtual-waterfall-container) {
      height: 100%;
    }

    .activity-image {
      width: 100%;
      object-fit: cover;
      border-radius: 8px 8px 0 0;
    }
  }

  .waterfall-container {
    min-height: 100%;
  }

  :deep(.waterfall-item) {
    break-inside: avoid;
    box-sizing: border-box;
  }

  .loading-status {
    text-align: center;
    padding: 16px 0;
    color: #999;
    font-size: 14px;

    .van-loading {
      margin: 0 auto;
    }

    .no-more {
      color: #999;
      font-size: 14px;
    }
  }

  .activity-image {
    width: 100%;
    object-fit: cover;
    border-radius: 8px 8px 0 0;
  }

  :deep(.fs-virtual-waterfall-container) {
    height: 100%;
    overflow-y: auto;
  }

  :deep(.fs-virtual-waterfall-item) {
    padding: 4px;
    box-sizing: border-box;
  }
}
</style>
